extends Node2D

## 角色类
class_name Character

## 角色名
@export var character_name: String = "";

## 血量
@export var hp: int = 1000:
	set(value):
		if value <= 0:
			value = 0
		hp = value
		emit_signal("hp_changed", value)
		if value == 0:
			emit_signal("dead")
			_on_dead()
## 攻击力
@export var atk: int = 10:
	set(value):
		atk = value
		emit_signal("atk_changed", value)
## 防御力
@export var def: int = 10:
	set(value):
		def = value
		emit_signal("def_changed", value)
## 持有金币
@export var money: int = 0:
	set(value):
		money = value
		emit_signal("money_changed", value)

## 动画节点
@export var fx : AnimatedSprite2D

## 攻击播放的音效
@export var sfx : AudioStream

@onready var hud = $"/root/LevelManager/HUD" as HUD

@onready var _audio: Audio = $"/root/LevelManager/Audio"

## 血量变更通知
signal hp_changed(hp)
## 攻击力变更通知
signal atk_changed(atk)
## 防御力变更通知
signal def_changed(def)
## 持有金币变更通知
signal money_changed(money)
## 死亡通知
signal dead()

## 向左移动
func move_left():
	self.move_to(Vector2(-16,0))

## 向右移动
func move_right():
	self.move_to(Vector2(16,0))

## 向上移动
func move_up():
	self.move_to(Vector2(0,-16))

## 向下移动
func move_down():
	self.move_to(Vector2(0,16))

## 移动到指定位置
func move_to(pos: Vector2):
	var result = await self._on_move(pos)
	if result:
		self.position += pos
	return result

## 攻击另一个角色
func attack(character2: Character) -> int:
	await self._play_character_fx(character2)
	if self.sfx != null:
		self._audio.play_sfx(self.sfx, 10)
	return self.atk - character2.def

## 移动回调，返回false则不移动
func _on_move(pos: Vector2):
	return true

## 死亡回调
func _on_dead():
	pass

## 播放角色动画效果
func _play_character_fx(character: Character):
	if character.fx == null:
		return
	character.fx.visible = true
	character.fx.play()
	await character.fx.animation_finished
	character.fx.visible = false
